<script setup lang="ts">
import type {
  CustomStatusDefinition,
  ResourceTypeCustomStatus,
} from '#/api/resource-center/status-types';

import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

import {
  createCustomStatusDefinition,
  deleteCustomStatusDefinition,
  getCustomStatusDefinitions,
  getResourceTypeCustomStatus,
  saveResourceTypeCustomStatus,
  updateCustomStatusDefinition,
} from '#/api/resource-center/custom-status-api';

// Props
interface Props {
  resourceType: string;
}

const props = defineProps<Props>();

// 响应式数据
const loading = ref(false);
const showCreateModal = ref(false);
const showStateMachineModal = ref(false);
const activeTab = ref('events');
const editingStatus = ref<CustomStatusDefinition | null>(null);
const statusDefinitions = ref<CustomStatusDefinition[]>([]);
const stateMachineEvents = ref<any[]>([]);

// 表单数据
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  color: '#1890ff',
  icon: '',
  isInitial: false,
  isFinal: false,
  allowedTransitions: [] as string[],
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入状态名称' }],
  code: [{ required: true, message: '请输入状态代码' }],
};

// 表格列定义
const columns = [
  { title: '状态名称', dataIndex: 'name', key: 'name' },
  { title: '状态代码', dataIndex: 'code', key: 'code' },
  { title: '显示', key: 'color' },
  { title: '初始状态', key: 'isInitial' },
  { title: '终态', key: 'isFinal' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 120 },
];

// 事件表格列定义
const eventColumns = [
  { title: '事件名称', dataIndex: 'name', key: 'name' },
  { title: '起始状态', key: 'from' },
  { title: '目标状态', key: 'to' },
  { title: '操作', key: 'action', width: 80 },
];

// 计算属性
const statusOptions = computed(() =>
  statusDefinitions.value.map((item) => ({
    label: item.name,
    value: item.code,
  })),
);

const transitionOptions = computed(() =>
  statusDefinitions.value
    .filter((item) => item.id !== editingStatus.value?.id)
    .map((item) => ({
      label: item.name,
      value: item.code,
    })),
);

// 方法
const loadStatusDefinitions = async () => {
  loading.value = true;
  try {
    const response = await getCustomStatusDefinitions();
    statusDefinitions.value = response.data || [];
  } catch {
    message.error('加载状态定义失败');
  } finally {
    loading.value = false;
  }
};

const loadStateMachineConfig = async () => {
  try {
    const response = await getResourceTypeCustomStatus(props.resourceType);
    if (response.data?.stateMachine?.events) {
      stateMachineEvents.value = response.data.stateMachine.events;
    }
  } catch {
    // 如果没有配置，使用空数组
    stateMachineEvents.value = [];
  }
};

const saveStatus = async () => {
  try {
    await formRef.value.validate();

    if (editingStatus.value) {
      await updateCustomStatusDefinition(editingStatus.value.id, formData);
      message.success('状态定义更新成功');
    } else {
      await createCustomStatusDefinition(formData as CustomStatusDefinition);
      message.success('状态定义创建成功');
    }

    showCreateModal.value = false;
    resetForm();
    loadStatusDefinitions();
  } catch {
    message.error('保存失败');
  }
};

const editStatus = (record: CustomStatusDefinition) => {
  editingStatus.value = record;
  Object.assign(formData, record);
  showCreateModal.value = true;
};

const deleteStatus = async (id: string) => {
  try {
    await deleteCustomStatusDefinition(id);
    message.success('删除成功');
    loadStatusDefinitions();
  } catch {
    message.error('删除失败');
  }
};

const resetForm = () => {
  editingStatus.value = null;
  formRef.value?.resetFields();
  Object.assign(formData, {
    id: '',
    name: '',
    code: '',
    description: '',
    color: '#1890ff',
    icon: '',
    isInitial: false,
    isFinal: false,
    allowedTransitions: [],
  });
};

const addEvent = () => {
  stateMachineEvents.value.push({
    name: '',
    from: [],
    to: '',
    conditions: [],
    actions: [],
  });
};

const removeEvent = (index: number) => {
  stateMachineEvents.value.splice(index, 1);
};

const saveStateMachine = async () => {
  try {
    const config: ResourceTypeCustomStatus = {
      resourceType: props.resourceType,
      statusDefinitions: statusDefinitions.value,
      stateMachine: {
        name: `${props.resourceType}状态机`,
        description: `${props.resourceType}资源的状态机配置`,
        version: '1.0.0',
        events: stateMachineEvents.value,
      },
    };

    await saveResourceTypeCustomStatus(props.resourceType, config);
    message.success('状态机配置保存成功');
    showStateMachineModal.value = false;
  } catch {
    message.error('保存状态机配置失败');
  }
};

const generateDiagram = () => {
  message.info('状态图生成功能开发中...');
};

// 生命周期
onMounted(() => {
  loadStatusDefinitions();
  loadStateMachineConfig();
});
</script>

<template>
  <div class="custom-status-manager">
    <a-card title="自定义状态管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showCreateModal = true">
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            新建状态定义
          </a-button>
          <a-button @click="showStateMachineModal = true">
            <template #icon>
              <IconifyIcon icon="ant-design:branches-outlined" />
            </template>
            状态机配置
          </a-button>
        </a-space>
      </template>

      <!-- 状态定义列表 -->
      <a-table
        :columns="columns"
        :data-source="statusDefinitions"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'color'">
            <a-tag :color="record.color">{{ record.name }}</a-tag>
          </template>
          <template v-else-if="column.key === 'isInitial'">
            <a-tag v-if="record.isInitial" color="green">初始状态</a-tag>
          </template>
          <template v-else-if="column.key === 'isFinal'">
            <a-tag v-if="record.isFinal" color="red">终态</a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editStatus(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个状态定义吗？"
                @confirm="deleteStatus(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 状态定义编辑模态框 -->
    <a-modal
      v-model:open="showCreateModal"
      :title="editingStatus ? '编辑状态定义' : '新建状态定义'"
      @ok="saveStatus"
      @cancel="resetForm"
    >
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="状态名称" name="name">
              <a-input
                v-model:value="formData.name"
                placeholder="请输入状态名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态代码" name="code">
              <a-input
                v-model:value="formData.code"
                placeholder="请输入状态代码"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入状态描述"
            :rows="3"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="颜色" name="color">
              <a-input v-model:value="formData.color" placeholder="#1890ff" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="图标" name="icon">
              <a-input
                v-model:value="formData.icon"
                placeholder="ant-design:check-circle"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="状态类型">
              <a-space>
                <a-checkbox v-model:checked="formData.isInitial">
                  初始状态
                </a-checkbox>
                <a-checkbox v-model:checked="formData.isFinal">终态</a-checkbox>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="允许转换的状态" name="allowedTransitions">
          <a-select
            v-model:value="formData.allowedTransitions"
            mode="multiple"
            placeholder="选择允许转换到的状态"
            :options="transitionOptions"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 状态机配置模态框 -->
    <a-modal
      v-model:open="showStateMachineModal"
      title="状态机配置"
      width="800px"
      @ok="saveStateMachine"
    >
      <a-tabs v-model:active-key="activeTab">
        <a-tab-pane key="events" tab="事件定义">
          <div class="state-machine-events">
            <a-button
              type="dashed"
              block
              @click="addEvent"
              style="margin-bottom: 16px"
            >
              <template #icon>
                <IconifyIcon icon="ant-design:plus-outlined" />
              </template>
              添加事件
            </a-button>

            <a-table
              :columns="eventColumns"
              :data-source="stateMachineEvents"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'from'">
                  <a-select
                    v-model:value="record.from"
                    mode="multiple"
                    placeholder="选择起始状态"
                    :options="statusOptions"
                    style="width: 100%"
                  />
                </template>
                <template v-else-if="column.key === 'to'">
                  <a-select
                    v-model:value="record.to"
                    placeholder="选择目标状态"
                    :options="statusOptions"
                    style="width: 100%"
                  />
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="link"
                    size="small"
                    danger
                    @click="removeEvent(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <a-tab-pane key="diagram" tab="状态图">
          <div class="state-machine-diagram">
            <div class="diagram-placeholder">
              <Icon
                icon="ant-design:branches-outlined"
                style="font-size: 48px; color: #d9d9d9"
              />
              <p>状态机图可视化</p>
              <a-button type="primary" @click="generateDiagram">
                生成状态图
              </a-button>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.custom-status-manager {
  .state-machine-events {
    .ant-table {
      .ant-table-tbody > tr > td {
        padding: 8px;
      }
    }
  }

  .state-machine-diagram {
    .diagram-placeholder {
      text-align: center;
      padding: 40px;
      color: #999;

      p {
        margin: 16px 0;
        font-size: 14px;
      }
    }
  }
}
</style>
